package com.vf.cloud.paas.common.log.aspect;


import com.vf.cloud.paas.app.master.common.domain.UserLog;
import com.vf.cloud.paas.common.log.event.SysLogEvent;
import com.vf.cloud.paas.common.log.util.SysLogUtils;
import com.vf.cloud.paas.common.util.DateUtil;
import com.vf.cloud.paas.common.util.SpringContextHolder;

import lombok.SneakyThrows;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class SysLogAspect {

	@Around("@annotation(sysLog)")
	@SneakyThrows
	public Object around(ProceedingJoinPoint point, com.vf.cloud.paas.common.log.annotation.SysLog sysLog) {

		UserLog log = SysLogUtils.getSysLog();
		log.setTitle(sysLog.value());

		// 发送异步日志事件
		//Long startTime = System.currentTimeMillis();
		log.setCreateTime(DateUtil.getLocalDateTime());
		Object obj;
		try {
			obj = point.proceed();
			//log.setResponseContent(JsonKit.toJson(obj));
			//JSONObject r=JSONObject.parseObject(JSON.toJSONString(obj));
			//if(r!=null && r.containsKey("code") && r.containsKey("message")) {
				//log.setResponseCode(r.getInteger("code"));
				//log.setResponseMessage(r.getString("message"));
			//}
		}
		catch (Exception e) {
			//log.setException(e.getMessage());
			throw e;
		}
		finally {
			//Long endTime = System.currentTimeMillis();
			//log.setTime(endTime - startTime);
			//log.setUpdateTime(getDateTimeOfTimestamp(endTime));
			SpringContextHolder.publishEvent(new SysLogEvent(log));
		}

		return obj;
	}
	
	public static LocalDateTime getDateTimeOfTimestamp(long timestamp) {
	    Instant instant = Instant.ofEpochMilli(timestamp);
	    ZoneId zone = ZoneId.systemDefault();
	    return LocalDateTime.ofInstant(instant, zone);
	}
	
//	private Map<String, Object> getRequestParams(ProceedingJoinPoint proceedingJoinPoint) {
//		Map<String, Object> requestParams = new HashMap<String, Object>();
//		// 参数名
//		String[] paramNames = ((MethodSignature) proceedingJoinPoint.getSignature()).getParameterNames();
//		// 参数值
//		Object[] paramValues = proceedingJoinPoint.getArgs();
//		for (int i = 0; i < paramNames.length; i++) {
//			Object value = paramValues[i];
//			if (value instanceof MultipartFile) {
//				MultipartFile file = (MultipartFile) value;
//				value = file.getOriginalFilename(); // 获取文件名
//			}
//			requestParams.put(paramNames[i], value);
//		}
//		return requestParams;
//	}

}

